package 逆波兰表达式求值;

import java.util.Stack;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 逆波兰表达式求值
 * @date 2022/10/23 16:11
 */
public class Demo150 {
    public static void main(String[] args) {
        String[] tokens= {"4","13","5","/","+"};
        int i = evalRPN(tokens);
        System.out.println(i);
    }
    public static int evalRPN(String[] tokens) {
        Stack<String> stack=new Stack<>();
        for (String token : tokens) {
            if(token.equals("+")||token.equals("-")||token.equals("*")||token.equals("/")){
                String num1 = stack.pop();
                String num2 = stack.pop();
                String num3;
                if(token.equals("+")){
                     num3 = String.valueOf(Integer.parseInt(num2)+Integer.parseInt(num1));
                }else if(token.equals("-")){
                     num3 = String.valueOf(Integer.parseInt(num2)-Integer.parseInt(num1));
                }else if(token.equals("*")){
                     num3 = String.valueOf(Integer.parseInt(num2)*Integer.parseInt(num1));
                }else {
                     num3 = String.valueOf(Integer.parseInt(num2)/Integer.parseInt(num1));
                }
                stack.push(num3);
            }else {
                stack.push(token);
            }
        }
        return Integer.parseInt(stack.pop());
    }
}
